import React, { FC, ReactElement, useState, useEffect, ReactNode } from 'react';
import {
  Button,
  Table,
  Tag,
  Select,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Popconfirm,
  Typography,
} from 'antd';
import type { DatePickerProps } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Item, EditableCellProps } from '../index.d';
import { Moment } from 'moment';
import { dataFormat1 } from '@/untils/dictionaries';
import { handleMoney } from '../../../untils/index';
import { connect } from 'umi';

const { Option } = Select;
interface IProps {
  InnerEditTable: {
    tableData: Item[];
    selectedRowKeys: string[];
    total: number;
  };
  dispatch: FC;
}

function EditTable(props: IProps): ReactElement {
  console.log('执行表单');
  const {
    InnerEditTable: { tableData, selectedRowKeys, total },
    dispatch,
  } = props;

  const [form] = Form.useForm();
  const [editingKey, setEditingKey] = useState('');
  const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>(
    'checkbox',
  );
  const [projectCount, setProjectCount] = useState({ order: 0, orderCount: 0 }); //项目选中金额  隐藏
  const isEditing = (record: Item) => record.key === editingKey;
  // rowSelection object indicates the need for row selection
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: Item[]) => {
      dispatch({
        //选中列表的key
        type: 'InnerEditTable/changeSelectedRowKeys',
        payload: selectedRowKeys,
      });
      let count = 0;

      selectedRows.forEach((item) => (count += item.projectMoney));
      count = handleMoney(count); //处理一下金额
      setProjectCount({ order: selectedRowKeys.length, orderCount: count });
      console.log(selectedRowKeys, selectedRows, selectionType);
    },
    getCheckboxProps: (record: Item) => ({
      disabled: record.projectName === 'Disabled User', // Column configuration not to be checked
      name: record.projectName,
    }),
    selectedRowKeys,
  };
  const edit = (record: Partial<Item> & { key: React.Key }) => {
    form.setFieldsValue({ name: '', age: '', address: '', ...record });
    setEditingKey(record.key);
  };
  const cancel = () => {
    setEditingKey('');
  };
  const save = async (key: React.Key) => {
    try {
      const row = (await form.validateFields()) as Item;

      const newData = [...tableData];
      const index = newData.findIndex((item) => key === item.key);
      if (index > -1) {
        const item = newData[index];
        console.log(item, row);
        item.projectStartTimeLabel = row.projectStartTime.format(dataFormat1);
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        dispatch({
          type: 'InnerEditTable/changeTableData',
          payload: newData,
        });
        setEditingKey('');
      } else {
        newData.push(row);
        dispatch({
          type: 'InnerEditTable/changeTableData',
          payload: newData,
        });
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };
  const columns = [
    ...initColumns,
    {
      title: '操作',
      dataIndex: 'operation',
      Key: 'operation',
      render: (_: any, record: Item) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.key)}
              style={{ marginRight: 8 }}
            >
              Save
            </Typography.Link>
            <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
              <a>Cancel</a>
            </Popconfirm>
          </span>
        ) : (
          <Typography.Link
            disabled={editingKey !== ''}
            onClick={() => edit(record)}
          >
            Edit
          </Typography.Link>
        );
      },
    },
  ];
  const mergedColumns = columns.map((col, index) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: Item) => ({
        record,
        inputType: col.inputType,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <div>
      {selectedRowKeys.length ? (
        <p className="edit-table-project-count">
          已选择 <a>{projectCount.order}</a> 项 &nbsp;项目金额总计 :
          {projectCount.orderCount}
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <a
            onClick={() => {
              dispatch({
                //选中列表的key
                type: 'InnerEditTable/changeSelectedRowKeys',
                payload: [],
              });
            }}
          >
            清空
          </a>
        </p>
      ) : (
        ''
      )}
      <Form form={form} component={false}>
        <Table
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          rowSelection={{
            type: selectionType,
            ...rowSelection,
          }}
          bordered
          dataSource={tableData}
          columns={mergedColumns}
          rowClassName="editable-row"
          pagination={{
            onChange: cancel,
            total,
            showTotal: () => `共 ${total} 条`,
          }}
        />
      </Form>
    </div>
  );
}
export default connect(({ InnerEditTable }: any) => ({ InnerEditTable }))(
  EditTable,
);
const selectStatus = [
  { value: '服务1', label: '服务1' },
  { value: '服务2', label: '服务2' },
  { value: '服务3', label: '服务3' },
  { value: '服务4', label: '服务4' },
];
const serviceContentChildren: React.ReactNode[] = [];
for (let i = 10; i < 36; i++) {
  serviceContentChildren.push(
    <Option key={'服务内容' + i}>{'服务内容' + i}</Option>,
  );
}

const projectPrincipalChildren: React.ReactNode[] = [];
for (let i = 10; i < 36; i++) {
  projectPrincipalChildren.push(
    <Option key={'负责人' + i}>{'负责人' + i}</Option>,
  );
}

const handleChange = (value: string[]) => {
  console.log(`selected ${value}`);
};
const EditableCell: React.FC<EditableCellProps> = (item) => {
  const {
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  } = item;
  let inputNode = null;
  switch (inputType) {
    case 'number':
      inputNode = <InputNumber />;
      break;
    case 'text':
      inputNode = <Input />;
      break;
    case 'projectPrincipal':
      inputNode = (
        <Select
          mode="multiple"
          allowClear
          style={{ width: 100 }}
          placeholder="Please select"
          defaultValue={['a10', 'c12']}
          onChange={handleChange}
        >
          {projectPrincipalChildren}
        </Select>
      );
      break;
    case 'serviceContent':
      inputNode = (
        <Select
          mode="multiple"
          allowClear
          style={{ width: 100 }}
          placeholder="Please select"
          defaultValue={['a10', 'c12']}
          onChange={handleChange}
        >
          {serviceContentChildren}
        </Select>
      );
      break;
    case 'serviceType':
      inputNode = (
        <Select placeholder="请选择" style={{ width: 100 }}>
          {selectStatus.map((item) => (
            <Option value={item.value} key={item.value}>
              {item.label}
            </Option>
          ))}
        </Select>
      );
      break;
    case 'DatePicker':
      const onChange: DatePickerProps['onChange'] = (date, dateString) => {
        console.log(date, dateString, record, item);
      };
      inputNode = <DatePicker onChange={onChange} />;
      break;
    default:
      inputNode = <Input />;
      break;
  }

  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};
const initColumns = [
  {
    title: '项目编号',
    key: 'projectID',
    dataIndex: 'projectID',
    editable: true,
    width: 130,
  },
  {
    title: '项目名称',
    Key: 'projectName',
    dataIndex: 'projectName',
    editable: true,
    width: 150,
  },
  {
    title: '地址',
    dataIndex: 'projectAddress',
    Key: 'projectAddress',
    editable: true,
    width: 200,
  },
  {
    title: '负责人',
    dataIndex: 'projectPrincipal',
    Key: 'projectPrincipal',
    inputType: 'projectPrincipal',
    editable: true,
    render: (_, record: Item) => {
      return record.projectPrincipal.map((item) => (
        <Tag key={item}>{item}</Tag>
      ));
    },
  },
  {
    title: '项目金额',
    dataIndex: 'projectMoney',
    Key: 'projectMoney',
    //   defaultSortOrder: 'descend',//默认升序
    sorter: (a, b) => a.projectMoney - b.projectMoney,
    editable: true,
    inputType: 'number',
    width: 100,
  },
  {
    title: '开始时间',
    dataIndex: 'projectStartTime',
    Key: 'projectStartTime',
    editable: true,
    inputType: 'DatePicker',
    render: (_, record: Item) => (
      <span>{record.projectStartTime.format(dataFormat1)}</span>
    ),
  },
  {
    title: '服务内容',
    dataIndex: 'serviceContent',
    Key: 'serviceContent',
    inputType: 'serviceContent',
    editable: true,
    render: (_, record: Item) => {
      return record.serviceContent.map((item) => <Tag key={item}>{item}</Tag>);
    },
  },
  {
    title: '服务类型',
    dataIndex: 'serviceType',
    Key: 'serviceType',
    inputType: 'serviceType',
    editable: true,
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'projectStatusLabel',
    Key: 'projectStatusLabel',
    editable: true,
    width: 100,
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    Key: 'operator',
    editable: true,
    width: 100,
  },
  {
    title: '操作时间',
    dataIndex: 'operaTime',
    Key: 'operaTime',
    editable: true,
    width: 100,
  },
];
